import os
from flask import Flask, request, jsonify

app = Flask(__name__)

# 上传文件保存目录
UPLOAD_FOLDER = '/opt/twin'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)  # 确保目录存在
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 允许的文件扩展名（按需修改）
ALLOWED_EXTENSIONS = {'ply', 'png', 'jpg', 'jpeg'}


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    if file and allowed_file(file.filename):
        # 保存文件
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)

        # 设置文件权限为 755 (rwxr-xr-x)
        os.chmod(filepath, 0o755)

        return jsonify({
            "message": "File uploaded successfully",
            "filename": file.filename,
            "path": filepath
        }), 200
    else:
        return jsonify({"error": "File type not allowed"}), 400


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)